package com.icare.common.service.db;

import com.alibaba.druid.pool.DruidDataSource;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

/**
 * druid数据库链接密码加密解密类
 *
 * @author TianHaibo
 * @create 2017-12-06 11:36
 **/
public class SecureDruidDataSource extends DruidDataSource{

    private static final String SECURE_KEY = "@icare1234567@~!";
    private static final String SECURE_IV = "~$#^@tianhaibo@#";
    private static final long serialVersionUID = 6329179268029213927L;

    public SecureDruidDataSource() {
    }

    public void setPassword(String password) {
        String plaintPassword = null;

        try {
            plaintPassword = this.decryptPassword(password);
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        super.setPassword(plaintPassword);
    }

    public String encryptPassword() throws Exception {
        Key keySpec = new SecretKeySpec(SECURE_KEY.getBytes(), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(SECURE_IV.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(1, keySpec, ivSpec);
        byte[] b = cipher.doFinal(this.password.getBytes());
        String ret = Base64.getEncoder().encodeToString(b);
        return ret;
    }

    public String decryptPassword(String password) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(password);
        IvParameterSpec ivSpec = new IvParameterSpec(SECURE_IV.getBytes());
        Key key = new SecretKeySpec(SECURE_KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(2, key, ivSpec);
        byte[] ret = cipher.doFinal(bytes);
        return new String(ret, "utf-8");
    }

    public static void main(String[] args) {
        SecureDruidDataSource secureDruidDataSource = new SecureDruidDataSource();
        secureDruidDataSource.password = "root";
        try {
            System.out.println(secureDruidDataSource.encryptPassword());
            System.out.println(secureDruidDataSource.decryptPassword("tW7DZkNISd1RkV4Orf5yGw=="));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
